package com.wx.demo.command;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryType;
import java.util.List;
import java.util.Objects;

public class MemoryCommand {

    public static void printMemory() {
        //获取所有内存信息
        List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans();

        System.out.println("堆内存：");
        //打印堆内存
        getMemoryInfo(memoryPoolMXBeans, MemoryType.HEAP);

        System.out.println("非堆内存：");
        //打印非堆内存
        getMemoryInfo(memoryPoolMXBeans, MemoryType.NON_HEAP);


    }

    private static void getMemoryInfo(List<MemoryPoolMXBean> memoryPoolMXBeans, MemoryType memoryType) {
        memoryPoolMXBeans.stream().filter(x -> Objects.equals(x.getType(), memoryType))
                .forEach(x -> {
                    StringBuilder str = new StringBuilder();
                    str.append("name:")
                            .append(x.getName())
                            .append("used:")
                            .append(x.getUsage().getUsed() /1024/1024)
                            .append("committed:")
                            .append(x.getUsage().getCommitted() /1024/1024)
                            .append("max:")
                            .append(x.getUsage().getMax() /1024/1024);
                    System.out.println(str);
                });
    }
}
